package com.mornd.gulimall.member.controller;

import com.mornd.gulimall.apis.member.to.MemberLoginTo;
import com.mornd.gulimall.apis.member.to.MemberRegistTo;
import com.mornd.gulimall.common.core.entity.SessionUser;
import com.mornd.gulimall.common.core.exception.ExistedException;
import com.mornd.gulimall.common.core.exception.LoginFailException;
import com.mornd.gulimall.common.core.result.R;
import com.mornd.gulimall.member.service.IMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <p>
 * 会员 前端控制器
 * </p>
 *
 * @author mornd
 * @since 2023-07-31
 */

@Slf4j
@RestController
@RequestMapping("/member/member")
public class MemberController {
    @Resource
    private IMemberService memberService;

    @PostMapping("/regist")
    public R regist(@RequestBody @Validated MemberRegistTo to) {
        try {
            memberService.regist(to);
        } catch (ExistedException e) {
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.fail("服务器异常");
        }
        return R.ok();
    }

    @PostMapping("/login")
    public R<SessionUser> login(@RequestBody @Validated MemberLoginTo to) {
        try {
            SessionUser sessionUser = memberService.login(to);
            return R.ok(sessionUser);
        } catch (LoginFailException e) {
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.fail("登录失败，服务器异常");
        }
    }
}
